package com.ycwl.freetv.utils;

import android.os.Environment;
import android.os.StatFs;

import java.io.File;

public class SystemUtils {
    /**
     * 获取手机内部存储空间剩余大小
     * @return
     */
    public long getAvailableInternalStorageSpace() {
        // 获取内部存储的路径
        File path = Environment.getDataDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize, availableBlocks;

        // 获取block的大小
        blockSize = statFs.getBlockSizeLong();
        // 获取可用的block数量
        availableBlocks = statFs.getAvailableBlocksLong();

        // 返回可用空间大小，单位是字节
        return availableBlocks * blockSize;
    }

    /**
     * 获取外边存储剩余空间大小（如sd卡）
     * @return
     */
    public long getAvailableExternalStorageSpace() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File path = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(path.getPath());
            long blockSize, availableBlocks;

            blockSize = statFs.getBlockSizeLong();
            availableBlocks = statFs.getAvailableBlocksLong();

            return availableBlocks * blockSize;
        } else {
            return -1; // 外部存储不可用或未挂载
        }
    }

    public static long getAvailableExternalStorageSpace(File externalStorageDirectory) {
        // 获取外部存储的根目录
        StatFs statFs = new StatFs(externalStorageDirectory.getPath());
        long blockSize, availableBlocks;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // 在API 18及以上使用此方法
            availableBlocks = statFs.getAvailableBlocksLong();
            blockSize = statFs.getBlockSizeLong();
        } else {
            // 在API 18以下使用此方法
            availableBlocks = statFs.getAvailableBlocks();
            blockSize = statFs.getBlockSize();
        }

        // 剩余空间大小
        return availableBlocks * blockSize;
    }
}
